<div class="layui-form">
<div class="layui-layer-outerbox" style="margin-bottom:80px">
    <div class="layui-form-item">
        <label class="layui-form-label"><span style="color:red">*</span> 模型名称</label>
        <div class="layui-input-block">
            <input type="hidden" name="{{makeElUniqueName('model_id')}}" value="{{ isset($model)?$model->id:'' }}">
            <input type="text" name="{{makeElUniqueName('model_name')}}" value="{{ isset($model)?$model->name:'' }}" required lay-verify="required" placeholder="模型的显式名称，可以是多个名称组合而成，必填（*）" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">所属类目</label>
        <div class="layui-input-block">
            <select name="{{makeElUniqueName('class_category')}}0" lay-filter="{{makeElUniqueName('class_category')}}0" cate-index='0'>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label"><span style="color:red">*</span> 模型文件</label>
        <div class="layui-input-block">
            <div id="modelUploader" class="t-uploader">                    
                <div class="t-btns">
                    <div id="picker" class="webuploader-container"></div>
                    <button id="uploadBtn" class="layui-btn layui-btn-small layui-btn-normal">开始上传</button>
                    <input type="hidden" id="{{makeElUniqueName('hidUploader')}}">
                </div>
                <div class="t-file-info"></div>
                <div class="t-upload-progress">
                    <div class="layui-progress layui-progress-big" lay-filter="pg-model" lay-showPercent="true">
                        <div class="layui-progress-bar layui-bg-orange"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label"><span style="color:red">*</span> 缩略图</label>
        <div class="layui-input-block">
            <div class="layui-big-upload-box" style="height:300px;width:100%">
                <input type="hidden" name="{{makeElUniqueName('thumb_id')}}" value="">
                <img id="{{makeElUniqueName('img_thumb_new')}}" style="height:300px;width:100%" src="/images/no-pic-back.png">
                <div class="site-demo-upbar">
                    <input type="file" name="{{makeElUniqueName('thumb_img')}}" class="layui-upload-file" id="{{makeElUniqueName('thumb_img')}}">
                </div>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">轮播图<br><div style="color:red">(1-5张)</div></label>
        <div class="layui-input-block">
            <div id="wrapperThumb" class="m-wrapper">
                <div id="containerThumb" class="m-container">
                    <!--头部，相册选择和格式选择-->

                    <div id="uploaderThumb" class="m-uploader">
                        <div class="queueList">
                            <div id="dndAreaThumb" class="placeholder">
                                <div id="filePickerThumb"></div>
                                <p>或将照片拖到这里，单次最多可选300张</p>
                            </div>
                        </div>
                        <div class="statusBar" style="display:none;">
                            <div class="progress">
                                <span class="text">0%</span>
                                <span class="percentage"></span>
                            </div><div class="info"></div>
                            <div class="btns">
                                <div id="filePicker2Thumb" class="m-addbutton"></div><input type="hidden" id="guidFieldThumb"><input type="hidden" id="successfilesThumb"><div class="uploadBtn">开始上传</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">线框图<br><div style="color:red">(1-3张)</div></label>
        <div class="layui-input-block">
            <div id="wrapperLine" class="m-wrapper">
                <div id="containerLine" class="m-container">
                    <!--头部，相册选择和格式选择-->

                    <div id="uploaderLine" class="m-uploader">
                        <div class="queueList">
                            <div id="dndAreaLine" class="placeholder">
                                <div id="filePickerLine"></div>
                                <p>或将照片拖到这里，单次最多可选300张</p>
                            </div>
                        </div>
                        <div class="statusBar" style="display:none;">
                            <div class="progress">
                                <span class="text">0%</span>
                                <span class="percentage"></span>
                            </div><div class="info"></div>
                            <div class="btns">
                                <div id="filePicker2Line" class="m-addbutton"></div><input type="hidden" id="guidFieldLine"><input type="hidden" id="successfilesLine"><div class="uploadBtn">开始上传</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div>
        <label class="layui-form-label"><span style="color:red">*</span> 模型价格</label>
        <div class="layui-input-block">
            <input type="text" placeholder="" name="{{makeElUniqueName('model_price')}}" required lay-verify="required" autocomplete="off" class="layui-input">
        </div>
    </div>
</div>
<div class="layui-dialog-bar">
    <button class="layui-btn" lay-submit lay-filter="{{makeElUniqueName('model_save')}}"><i class="layui-icon">&#xe605;</i> 保存</button>&nbsp;
    <button class="layui-btn layui-btn-primary" onclick="layer.close(layui.popLayerUtil.index);"><i class="layui-icon">&#x1006;</i>  关闭</button>
</div>
</div>

<script>
layui.use(['form', 'jquery', 'validator', 'multifileuploader', 'largefileuploader', 'uploadUtil'], function(){
var form = layui.form();
var $ = layui.jquery;
var popLayerUtil = layui.popLayerUtil;
var multifileuploader = layui.multifileuploader;
var largefileuploader = layui.largefileuploader;
var uploadUtil = layui.uploadUtil;

multifileuploader.init({
    uploader: 'uploaderThumb',
    paste: 'uploaderThumb',
    filePicker: 'filePickerThumb',
    addButton: 'filePicker2Thumb',
    successfiles: 'successfilesThumb',
    dnd: 'dndAreaThumb',
    guidField: 'guidFieldThumb'
});

multifileuploader.init({
    uploader: 'uploaderLine',
    paste: 'uploaderLine',
    filePicker: 'filePickerLine',
    addButton: 'filePicker2Line',
    successfiles: 'successfilesLine',
    dnd: 'dndAreaLine',
    guidField: 'guidFieldLine'
});

largefileuploader.init({
    uploader: 'modelUploader',
    filePicker: {
        id: 'picker',
        text: '选择模型'
    },
    uploadBtn: 'uploadBtn',
    pgfilter: 'pg-model',
    uploadId: '{{makeElUniqueName('hidUploader')}}'
});

uploadUtil.doUpload({
    success: function(fileId, filePath, fileKey) {
        if (fileKey == '{{makeElUniqueName('thumb_img')}}') {
            $('#{{makeElUniqueName('img_thumb_new')}}').attr('src', filePath);
            $('input[name=\'{{makeElUniqueName('thumb_id')}}\']').val(fileId);
        }
    }
});

layui.define(function(exports){
    var obj = {
        initCategoryData: function(parentId, depth, callback, defaultValue) {
            $('.layui-form-item[classes]').each(function() {
                $(this).remove();
            });

            $('.layui-form-item[class-props]').each(function() {
                $(this).remove();
            });
            
            if (depth == 0 || (parentId != 0 && depth > 0)) {
                var index = layer.load(1);
                var catename = '{{makeElUniqueName('class_category')}}';
                var modelname = '{{makeElUniqueName('model_class')}}';
                $.ajax({
                    contentType: "application/json",
                    type: 'post',
                    url: '/backstage/api/model-category/querylist',
                    data: JSON.stringify({
                        parentId: parentId
                    }),
                    success: function (outResult) {
                        layer.close(index);
                        $('.layui-form-item select[cate-index]').each(function() {
                            var cateIndex = parseInt($(this).attr('cate-index'));

                            if (cateIndex > depth) {
                                $(this).parent().parent().remove();
                            }
                        });

                        var target = null;
                        var filter = catename + depth;
                        if (parentId == 0) {
                            target = $('select[name=\'' + filter + '\']');

                            target.find('option').each(function(){
                                $(this).remove();
                            });

                            target.append($('<option>').attr('value', '0').text('(选择分类)'));

                            var cates = outResult.cates;
                            for (var i=0; i<cates.length; i++) {
                                var cate = cates[i];
                                if (defaultValue) {
                                    if (cate.id == defaultValue) {
                                        target.append($('<option>').attr('value', cate.id).attr('selected', 'selected').text(cate.name));
                                    } else {
                                        target.append($('<option>').attr('value', cate.id).text(cate.name));
                                    }
                                } else {
                                    target.append($('<option>').attr('value', cate.id).text(cate.name));
                                }
                            }

                            form.render();

                            form.on('select(' + filter + ')', function(data){
                                layui.modelCreateFuncs.initCategoryData(data.value, depth);
                            });

                            var classes = outResult.classes;

                            if (classes.length > 0) {
                                var html = '<div class="layui-form-item" classes><label class="layui-form-label">所属品类</label><div class="layui-input-block"><select name="' + modelname + '" lay-filter="' + modelname + '" lay-search></select></div></div>';

                                var formItem = $(html).insertAfter('.layui-form-item:has(select[name=\'' + filter + '\'])');

                                var classselect = $('select[name=\'' + modelname + '\']');

                                classselect.find('option').each(function(){
                                    $(this).remove();
                                });

                                classselect.append($('<option>').attr('value', '0').text('(选择品类)'));

                                for (var i=0; i<classes.length; i++) {
                                    var classItem = classes[i];
                                    classselect.append($('<option>').attr('value', classItem.id).text(classItem.name));
                                }

                                form.on('select(' + modelname + ')', function(data){
                                    layui.modelCreateFuncs.initCategoryData(data.value, newdepth);
                                });

                                form.on('select(' + modelname + ')', function(data){
                                    layui.modelCreateFuncs.changeClass(data.value, modelname);
                                });
                            }

                            form.render();
                        } else {
                            var cates = outResult.cates;

                            var lastSelectFilter = filter;

                            if (cates.length > 0) {
                                var newdepth = depth + 1;
                                var newSelect = catename + newdepth;
                                var html = '<div class="layui-form-item"><label class="layui-form-label"></label><div class="layui-input-block">';
                                html += '<select name="' + newSelect + '" lay-filter="' + newSelect + '" cate-index="' + newdepth + '" ></select></div></div>';

                                var formItem = $(html).insertAfter('.layui-form-item:has(select[name=\'' + filter + '\'])');
                                var select = $('select[name=\'' + newSelect + '\']');

                                select.find('option').each(function(){
                                    $(this).remove();
                                });

                                select.append($('<option>').attr('value', '0').text('(选择分类)'));

                          
                                for (var i=0; i<cates.length; i++) {
                                    var cate = cates[i];
                                    if (defaultValue) {
                                        if (cate.id == defaultValue) {
                                            select.append($('<option>').attr('value', cate.id).attr('selected', 'selected').text(cate.name));
                                        } else {
                                            select.append($('<option>').attr('value', cate.id).text(cate.name));
                                        }
                                    } else {
                                        select.append($('<option>').attr('value', cate.id).text(cate.name));
                                    }
                                }

                                form.on('select(' + newSelect + ')', function(data){
                                    layui.modelCreateFuncs.initCategoryData(data.value, newdepth);
                                });

                                lastSelectFilter = newSelect;
                            }

                            var classes = outResult.classes;

                            if (classes.length > 0) {
                                var html = '<div class="layui-form-item" classes><label class="layui-form-label">所属品类</label><div class="layui-input-block"><select name="' + modelname + '" lay-filter="' + modelname + '" lay-search></select></div></div>';

                                var formItem = $(html).insertAfter('.layui-form-item:has(select[name=\'' + lastSelectFilter + '\'])');

                                var classselect = $('select[name=\'' + modelname + '\']');

                                classselect.find('option').each(function(){
                                    $(this).remove();
                                });

                                classselect.append($('<option>').attr('value', '0').text('(选择品类)'));

                                for (var i=0; i<classes.length; i++) {
                                    var classItem = classes[i];
                                    classselect.append($('<option>').attr('value', classItem.id).text(classItem.name));
                                }

                                form.on('select(' + modelname + ')', function(data){
                                    layui.modelCreateFuncs.changeClass(data.value, modelname);
                                });
                            }

                            form.render('select');
                        }

                        if (callback) {
                            callback.call(this, depth, parentId);
                        }
                        
                    }

                });
            }
        },
        changeClass: function(classId, classSelectName) {
            $('.layui-form-item[class-props]').each(function() {
                $(this).remove();
            });

            if (classId != 0) {
                var index = layer.load(1);

                $.ajax({
                    contentType: "application/json",
                    type: 'post',
                    url: '/backstage/api/model-property/querylist',
                    data: JSON.stringify({
                        classId: classId
                    }),
                    success: function (outResult) {
                        layer.close(index);
                        
                        var lastObjJqSelector = '.layui-form-item:has(select[name=\'' + classSelectName + '\'])';
                        for (var i=0; i<outResult.length; i++) {
                            var prop = outResult[i];

                            var html = '<div class="layui-form-item" class-props><label class="layui-form-label">' + prop.name + '</label><div class="layui-input-block"><ul style="width:100%"></ul></div></div>';

                            var formItem = $(html).insertAfter(lastObjJqSelector);

                            var fields = prop.value.split(',');

                            lastObjJqSelector = '.layui-form-item[class-props]:last';

                            var fieldsContainer = $(lastObjJqSelector).find('div[class=\'layui-input-block\']');
                            for (var j=0; j<fields.length; j++) {
                                var kvField = fields[j].split(':');
                                fieldsContainer.append('<li style="display:inline-block;width:20%"><input type="checkbox" name="" title="' + kvField[1] + '" value="' + kvField[0] + '" ></li>');
                            }
                        }

                        form.render();

                        $('.layui-form-checkbox span').css('width', '60px');
                    }
                });
            }
        },
        doInitCategoryData: function(depth, parentId){
            @if (isset($model))

            var cates = [];
            @foreach ($modelCates as $cate)
            cates.push('{{$cate}}');
            @endforeach

            @endif

            if (depth < cates.length-1) {
                
                var newDepth = depth+1;
                if (depth == 0 && parentId == 0) {
                    newDepth = 0;
                }

                if (newDepth < cates.length) {
                    var curId = 0;

                    if (depth < cates.length - 1) {
                        curId = cates[depth + 1];

                    }
                    
                    if (newDepth < cates.length - 1) {
                        layui.modelCreateFuncs.initCategoryData(cates[depth], newDepth, layui.modelCreateFuncs.doInitCategoryData, curId);
                    } else {
                        //layui.modelCreateFuncs.initCategoryData(cates[depth], newDepth, function(){});
                    }
                    
                }
                
            }
        }
    };
    exports('modelCreateFuncs', obj);
});

@if (isset($model))

var cates = [];
@foreach ($modelCates as $cate)
cates.push('{{$cate}}');
@endforeach
layui.modelCreateFuncs.initCategoryData(0, 0, function(depth, parentId){
    layui.modelCreateFuncs.doInitCategoryData(depth, parentId);
}, cates[0]);
@else
layui.modelCreateFuncs.initCategoryData(0, 0, function(depth, parentId){

});
@endif

form.on('submit({{makeElUniqueName('model_save')}})', function(data){
    if ($('.layui-form-item[classes]').length == 0) {
        layer.msg('还没有选择模型所属品类', { icon: 5 });
    } else {
        var index = layer.load(1);
        var url = '/backstage/api/model/savenew';
        var postParam = {
            name: data.field['{{makeElUniqueName('model_name')}}'],
            class_id: data.field['{{makeElUniqueName('model_class')}}'],
            price: data.field['{{makeElUniqueName('model_price')}}'],
            main_image: data.field['{{makeElUniqueName('thumb_id')}}'],
            fileThumbs: $('#successfilesThumb').val(),
            fileThumbGuid: $('#guidFieldThumb').val(),
            fileLines: $('#successfilesLine').val(),
            fileLineGuid: $('#guidFieldLine').val(),
            modelGuid: $('#{{makeElUniqueName('hidUploader')}}').val()
        };

        var props = [];
        
        $('.layui-form-item[class-props]').each(function() {
            var chks = [];
            var name = $(this).find('label.layui-form-label').text();
            
            $(this).find('input[type=\'checkbox\']').each(function() {
                if ($(this).prop('checked')) {
                    chks.push({
                        id: $(this).attr('title'),
                        name: name
                    });
                }
            });

            props.push(chks);
        });

        postParam.props = JSON.stringify(props);

        $.ajax({
            contentType: "application/json",
            type: 'post',
            url: url,
            data: JSON.stringify(postParam),
            success: function (outResult) {
                layer.close(index);
                if (outResult.Success) {
                    layer.msg(outResult.Message, { icon: 6 });
                    layer.close(popLayerUtil.index);
                    popLayerUtil.onClose();
                } else {
                    layer.msg(outResult.Message, { icon: 5 });
                }
            },
            error: function (error) {
                layer.close(index);
                layui.validator.processValidateError(error);
            }
        });
        return false;
    }
});
});
</script>
